package jsyf.oa.service.device;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.contract.ContractMainDao;
import jsyf.oa.dao.device.DeviceOutBoundDao;
import jsyf.oa.dao.device.DeviceSampleDao;
import jsyf.oa.dao.device.DevicelogisticsDao;
import jsyf.oa.dao.system.AuditDao;
import jsyf.oa.dao.system.MessageDao;
import jsyf.oa.dao.system.MessageReceiverDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.contract.ContractMainEntity;
import jsyf.oa.entity.device.*;
import jsyf.oa.entity.system.AuditEntity;
import jsyf.oa.entity.system.MessageEntity;
import jsyf.oa.entity.system.MessageReceiverEntity;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.facade.device.DevicelogisticsFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.Device_AUDIT_STATE_MESSAGE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.Device_STATE_AUDIT;

/**
 * Created by y on 2018/6/28.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class DevicelogisticsService implements DevicelogisticsFacade{
    @Autowired
    private DevicelogisticsDao devicelogisticsDao;
    @Autowired
    private AttachModuleDao attachModuleDao;
    @Autowired
    private DeviceOutBoundDao deviceOutBoundDao;
    @Autowired
    private ContractMainDao contractMainDao;
    @Autowired
    private DeviceSampleDao deviceSampleDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private TokenDao tokenDao;
    @Override
    public String add(String jsonObject) {
        DevicelogisticsAttachEntity entity = JSON.toJavaObject(JSON.parseObject(jsonObject), DevicelogisticsAttachEntity.class);
        DevicelogisticsEntity devicelogisticsEntity=entity.getMain();
        devicelogisticsDao.removeByCondition(" AND SAMPLE_ID = ? ", new String[]{devicelogisticsEntity.getSampleId()});
        devicelogisticsDao.add(devicelogisticsEntity);
        String mainId = devicelogisticsEntity.getId();
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        /*获取司机证件附件*/
        List<AttachmentEntity> certificateList = entity.getCertificates();
        if (certificateList != null && certificateList.size() > 0) {
            for (AttachmentEntity attach : certificateList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(6);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        /*获取设备照片附件*/
        List<AttachmentEntity> devicePictures = entity.getDevicePictures();
        if (devicePictures != null && devicePictures.size() > 0) {
            for (AttachmentEntity attach : devicePictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(7);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        /*获取板车照片附件*/
        List<AttachmentEntity> drayPictures = entity.getDrayPictures();
        if (drayPictures != null && drayPictures.size() > 0) {
            for (AttachmentEntity attach : drayPictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(8);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        return devicelogisticsEntity.getId();
    }


    @Override
    public List<JSONObject> getDeviceTypeListBySampleId(String jsonObject) {
        JSONObject JSONObject = JSON.parseObject(jsonObject);
        String sampleId=JSONObject.getString("sampleId");
        return devicelogisticsDao.getJSONListByCondition("AND SAMPLE_ID=?",new Object[]{sampleId});
    }

    @Override
        public JSONObject outBound(String jsonObject) {
            DeviceOutBoundEntity entity = JSON.toJavaObject(JSON.parseObject(jsonObject), DeviceOutBoundEntity.class);
            List<JSONObject> jsonObjectList = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            DeviceOutBoundMainEntity deviceOutBoundMainEntity=entity.getMain();
            deviceOutBoundDao.add(deviceOutBoundMainEntity);
            String mainId = deviceOutBoundMainEntity.getId();
            int type=deviceOutBoundMainEntity.getType();
            DeviceSampleMainEntity deviceSampleMainEntity=(DeviceSampleMainEntity)deviceSampleDao.getIBaseEntityById(deviceOutBoundMainEntity.getSampleId());
            //deviceSampleMainEntity.setStoreAddress("");
            if(deviceOutBoundMainEntity.getType()==0){
                deviceSampleMainEntity.setState("交付在途");
                //主表添加审核信息
                //首先获取上级为第一审核人
                JSONObject audit= userDao.getFirstParent(deviceOutBoundMainEntity.getCreateUserId());
                //设置审核人
                deviceSampleMainEntity.setAuditName(audit.getString("name"));
                deviceSampleMainEntity.setAuditId(audit.getString("id"));
                deviceSampleMainEntity.setAuditAdvise("");
                //设置审核状态；
                deviceSampleMainEntity.setAuditFlag(0);
                if (deviceOutBoundMainEntity.getCreateUserId().equals("201711271733404C9DA1461F2421F828")) {
                    deviceSampleMainEntity.setAuditFlag(1);
                    deviceSampleMainEntity.setAuditId("201711271733404C9DA1461F2421F828");
                    deviceSampleMainEntity.setAuditName("曹国玉");
                    deviceSampleMainEntity.setAuditRoleName("后台管理");
                    deviceSampleMainEntity.setAuditTime(deviceSampleDao.getCurrentTime());
                    deviceSampleMainEntity.setAuditAdvise("");
                }
                //设置修改人
                deviceSampleMainEntity.setUpdateUserId(deviceOutBoundMainEntity.getCreateUserId());
                deviceSampleMainEntity.setUpdateUserName(deviceOutBoundMainEntity.getCreateUserName());
                auditDao.removeByCondition("AND MAIN_ID = ? ", new String[]{deviceSampleMainEntity.getId()});
                //审核表添加审核信息
                AuditEntity auditEntity=new AuditEntity();
                auditEntity.setModuleName("newDevice");
                auditEntity.setMainId(deviceSampleMainEntity.getId());
                auditEntity.setAuditFlag(deviceSampleMainEntity.getAuditFlag());
                auditEntity.setAuditAdvise("");
                auditEntity.setAuditorId(audit.getString("id"));
                auditEntity.setAuditorName(audit.getString("name"));
                auditEntity.setAuditSort(0);
                auditEntity.setAuditTime(auditDao.getCurrentTime());
                auditEntity.setRoleName(audit.getString("roleName"));
                auditDao.add(auditEntity);
                deviceSampleDao.update(deviceSampleMainEntity);
//企业号:给审核人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", deviceSampleMainEntity.getAuditId());
                msgObject.put("content", String.format(Device_STATE_AUDIT,
                        deviceSampleMainEntity.getAuditName(),
                        deviceSampleMainEntity.getModelName(),
                        deviceSampleMainEntity.getSequence(),
                        deviceOutBoundMainEntity.getCreateUserName(),
                        DateUtils.parse(deviceSampleDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                if (!deviceSampleMainEntity.getUpdateUserId().equals("201711271733404C9DA1461F2421F828")) {
//标记以前的审核人、申请人消息为已读
                    messageReceiverRead(deviceSampleMainEntity.getId(), 0);
                    messageReceiverRead(deviceSampleMainEntity.getId(), 2);
//付款成功后给申请人发消息，保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(deviceOutBoundMainEntity.getCreateUserId());
                    messageEntity.setCreateTime(deviceSampleDao.getCurrentTime());
                    messageEntity.setContent(String.format(Device_STATE_AUDIT,
                            deviceSampleMainEntity.getAuditName(),
                            deviceSampleMainEntity.getModelName(),
                            deviceSampleMainEntity.getSequence(),
                            deviceOutBoundMainEntity.getCreateUserName(),
                            DateUtils.parse(deviceSampleDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(deviceSampleMainEntity.getId());
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/page/device/sample/detail_new.html?pageType=look&&id=" + deviceSampleMainEntity.getId() + "&openType=dialog");
                    messageEntity.setOpenTitle(String.format(Device_AUDIT_STATE_MESSAGE, deviceOutBoundMainEntity.getCreateUserName()));
                    messageDao.add(messageEntity);

                    //保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(deviceSampleMainEntity.getAuditId());
                    messageReceiverEntity.setUserType(2);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);
                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                }
            }else if(deviceOutBoundMainEntity.getType()==1){
                deviceSampleMainEntity.setState("移库在途");
                deviceSampleDao.update(deviceSampleMainEntity);
            }else{
                deviceSampleMainEntity.setState("退货在途");
                deviceSampleDao.update(deviceSampleMainEntity);
            }

            attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId+type});
            setAttach(entity,mainId+type);
            JSONObject obj = new JSONObject();
            obj.put("id", String.valueOf(deviceOutBoundMainEntity.getType()));
            obj.put("message", jsonObjectList);
            return obj;
        }

    @Override
    public JSONObject updateOutRecord(String jsonData) {
        DeviceOutBoundEntity deviceOutBoundEntity = JSON.toJavaObject(JSON.parseObject(jsonData), DeviceOutBoundEntity.class);
        DeviceOutBoundMainEntity entity=deviceOutBoundEntity.getMain();
        DeviceOutBoundMainEntity oldEntity=(DeviceOutBoundMainEntity)deviceOutBoundDao.getIBaseEntityById(entity.getId());
        entity.setCreateTime(oldEntity.getCreateTime());
        String moduleId=entity.getId()+"0";
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{moduleId});
        setAttach(deviceOutBoundEntity,moduleId);
        int rows = deviceOutBoundDao.update(entity);
        JSONObject obj = new JSONObject();
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }
    @Override
    public JSONObject updateExitRecord(String jsonData) {
        DeviceOutBoundEntity deviceOutBoundEntity = JSON.toJavaObject(JSON.parseObject(jsonData), DeviceOutBoundEntity.class);
        DeviceOutBoundMainEntity entity=deviceOutBoundEntity.getMain();
        DeviceOutBoundMainEntity oldEntity=(DeviceOutBoundMainEntity)deviceOutBoundDao.getIBaseEntityById(entity.getId());
        entity.setCreateTime(oldEntity.getCreateTime());
        String moduleId=entity.getId()+"2";
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{moduleId});
        setAttach(deviceOutBoundEntity,moduleId);
        int rows = deviceOutBoundDao.update(entity);
        JSONObject obj = new JSONObject();
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }
    @Override
    public JSONObject updateMoveRecord(String jsonData) {
        DeviceOutBoundEntity deviceOutBoundEntity = JSON.toJavaObject(JSON.parseObject(jsonData), DeviceOutBoundEntity.class);
        DeviceOutBoundMainEntity entity=deviceOutBoundEntity.getMain();
        DeviceOutBoundMainEntity oldEntity=(DeviceOutBoundMainEntity)deviceOutBoundDao.getIBaseEntityById(entity.getId());
        entity.setCreateTime(oldEntity.getCreateTime());
        String moduleId=entity.getId()+"1";
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{moduleId});
        setAttach(deviceOutBoundEntity,moduleId);
        int rows = deviceOutBoundDao.update(entity);
        JSONObject obj = new JSONObject();
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }
    public  void setAttach(DeviceOutBoundEntity entity,String moduleId){
        //获取司机证件附件
        List<AttachmentEntity> certificateList = entity.getCertificates();
        if (certificateList != null && certificateList.size() > 0) {
            for (AttachmentEntity attach : certificateList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(6);
                attachModuleEntity.setModuleId(moduleId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        } /*获取设备照片附件*/
        List<AttachmentEntity> devicePictures = entity.getDevicePictures();
        if (devicePictures != null && devicePictures.size() > 0) {
            for (AttachmentEntity attach : devicePictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(7);
                attachModuleEntity.setModuleId(moduleId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }/*获取板车照片附件*/
        List<AttachmentEntity> drayPictures = entity.getDrayPictures();
        if (drayPictures != null && drayPictures.size() > 0) {
            for (AttachmentEntity attach : drayPictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(8);
                attachModuleEntity.setModuleId(moduleId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
    }
    private void messageReceiverRead(String mainId, Integer userType) {
        StringBuffer sb = new StringBuffer();
        List<String> arg = new ArrayList<>();
        if (!org.apache.commons.lang3.StringUtils.isBlank(mainId)) {
            sb.append("AND mainId=?");
            arg.add(mainId);
        }
        if (null != userType) {
            sb.append("AND receiverUserType=?");
            arg.add(userType.toString());
        }
        String receiverIds = "";
        List<JSONObject> jsonObjectList = messageDao.getViewJSONListByCondition(sb.toString(), arg.toArray());
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            for (int i = 0; i < jsonObjectList.size(); i++) {
                receiverIds += "'" + jsonObjectList.get(i).getString("receiverId") + "',";
            }
        }
        if (receiverIds.length() > 1) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = null;
        }
        if (!org.apache.commons.lang3.StringUtils.isBlank(receiverIds)) {
            messageReceiverDao.updateReadFlag("T_SYS_MESSAGE_RECEIVER", "AND ID IN (" + receiverIds + ")");
        }
    }
    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }
}
